package com.cysion.study.ui.personal

import android.graphics.Bitmap
import android.text.TextUtils
import android.view.View
import com.cysion.other.color
import com.cysion.study.R
import com.cysion.study.helper.UserCache
import com.cysion.study.ktbox.Box
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.ACache
import com.cysion.study.ktbox.utils.whiteTextTheme
import com.cysion.study.net.ApiClient
import com.cysion.study.net.Urls
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.widget.BasePicActivity
import com.cysion.study.widget.FlowLayoutForPulish
import com.cysion.study.widget.ShowToast
import com.cysion.study.widget.VersionUtil
import com.cysion.study.widget.http.HttpUtil
import com.cysion.targetfun._subscribe
import com.loopj.android.http.JsonHttpResponseHandler
import com.loopj.android.http.RequestParams
import kotlinx.android.synthetic.main.activity_about.*
import kotlinx.android.synthetic.main.activity_comment_detail.*
import kotlinx.android.synthetic.main.activity_feedback.*
import kotlinx.android.synthetic.main.activity_feedback.fl_pics
import kotlinx.android.synthetic.main.activity_feedback.topbar
import org.json.JSONObject
import java.io.File
import java.lang.StringBuilder
import java.util.*

/**
 * Created by chu on 2019-07-01.
 */
class FeedBackActivity:BasePicActivity(), View.OnClickListener {


    override fun getLayoutId(): Int = R.layout.activity_feedback

    override fun initView() {
        whiteTextTheme(color(R.color.main_cl))
        topbar.apply {
            setTitle("举报与投诉")
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                }
            }
        }
        tv_submit.setOnClickListener(this)
        initFlowLayoutForPulishListener()

    }

    private val selectPics = ArrayList<String>()
    private fun initFlowLayoutForPulishListener() {
//        fl_pics.setShow(false)
        fl_pics.setShowData(false,selectPics,false,true)
        fl_pics.setonFlowLayoutForPulishListener(object :
            FlowLayoutForPulish.OnFlowLayoutForPulishListener {
            override fun add() {
                if (selectPics.size >= 3) {
                    ShowToast("最多不能超过3张图片")
                    return
                }
                takePhoto()
            }

            override fun delete(item: FlowLayoutForPulish.Item) {
//                selectPics.removeAt(item.index)
                selectPics.remove(item.path)
            }

            override fun onClick(item: FlowLayoutForPulish.Item) {
                val list = ArrayList<String>()
                list.add(item.path)
//                list.add(getFileUrl(item.path))
                //                PhotoPagerActivity.gotoActivity(_activity, list, 0);//预览大图
            }
        })
    }

    override fun outputBitmap(bitmap: Bitmap?, path: String?) {
        super.outputBitmap(bitmap, path)
        uploadPic(File(path))
    }
    private var index = 0
    private fun uploadPic(headUrl: File) {
        val params = RequestParams()
        params.put("file", headUrl)
        params.put("token", ACache.get(Box.context).getAsString("token"))
        var url= Urls.uploadPicture
        println("上传图片接口=="+url)
        HttpUtil.post1(url, params, object : JsonHttpResponseHandler() {
            override fun onSuccess(statusCode: Int, headers: Array<out org.apache.http.Header>?, response: JSONObject?) {
                super.onSuccess(statusCode, headers, response)
                Alert.close()
                try {
                    if (response?.getString("code") == "0") {
                        println("上传图片返回=${response.getString("data")}")
//                        var obj: String? = response.getString("data")
                        selectPics.add(response.getString("data"))//把图片添加到list
//                        fl_pics.addLocationPic(index, false, response.getString("data"))//显示图片
                        fl_pics.setShowData(false,selectPics,false,true)
                        index++
                    } else {
                        ShowToast("上传失败")
                        Alert.close()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                } finally {
                    Alert.close()
//                    ShowDialog.dissmiss()
                }
            }
            override fun onFinish() {
                Alert.close()
            }

            override fun onFailure(statusCode: Int, headers: Array<out org.apache.http.Header>?, responseString: String?, throwable: Throwable?) {
                super.onFailure(statusCode, headers, responseString, throwable)
                println("####上传失败"+statusCode+"##="+responseString)
                Alert.close()
            }
        })
    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_submit->{
                var content =et_comment.text.toString().trim()
                if (TextUtils.isEmpty(content)) {
                    ShowToast("请输入内容")
                    return
                }
                var img=""
                var sb = StringBuilder()
                if (selectPics != null && selectPics.size > 0) {
                    for (im in selectPics) {
                        sb.append(","+im)
                    }
                }
                if (sb.length > 1) {
                    sb.deleteCharAt(0)
                }
                var version= VersionUtil.getAppVersionName()
                Alert.loading(this)
                ApiClient.api.submitComplaint(content,sb.toString(),"安卓","安卓",version.toString(), UserCache.token).compose(BaseResponseRx.validateToMain())
                    ._subscribe {
                        _onNext {
                            Alert.close()
                            ShowToast("提交成功")
                            finish()
                        }
                        _onError {
                            Alert.close()
                            ShowToast(ErrorHandler.handle(it).errorMsg)
                        }
                    }
            }
        }

    }

    override fun closeMvp() {
    }
}